import { Button, Modal as ModalAntd, Select, Radio, Form, message } from 'antd';
import { FC, ReactText, useEffect, useState, useMemo, useRef, useCallback } from 'react';
import { useQueryFields } from '@inbiz/hooks';
import { useForm, useField } from '@formily/react';
import EditableTable from '@inbiz/basic/EditableTable';
import { uuid } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';
import './style.less';
const { Option } = Select;

const prefixCls = 'inbiz-Transfer-designer-configModal';

export interface DataType {
  key: ReactText;
  field: string;
  label: string;
}

type IType = 'list' | 'tree';

export type IValue = {
  type: IType;
  searchKey?: string;
  currentIdField?: string;
  parentIdField?: string;
  labelField?: string;
  fieldOptions?: DataType[];
};
interface IProps {
  value: IValue;
  update: string;
  onChange: (v: IValue) => void;
}

type TFormItem = {
  name: string;
};
interface ILocale {
  modalTitle: string;
  title: string;
  requiredmessage: string;
  formitem: {
    type: TFormItem & { valuelist: string; valuetree: string };
    currentidfield: TFormItem;
    currentlabelfield: TFormItem;
    parentidfield: TFormItem;
    searchkey: TFormItem;
  };
}

const ConfigModal: FC<IProps> = ({ value, update, onChange }) => {
  const tableRef = useRef<any>();
  const globalForm = useForm();
  const [form] = Form.useForm();
  const takeMessage = useField().takeMessage() as ILocale;
  const [visible, setVisible] = useState(false);
  const [type, setType] = useState<IType>('list');
  const [fieldOptions, setFieldOptions] = useState<DataType[]>([]);

  const [fields] = useQueryFields(
    {
      key: globalForm.fields?.['form.senior.soure.x-component-props.sourceModel']?.value,
      appId: globalForm.appInfo.appId,
    },
    [update],
  );
    
  const FormOtions = [
    {
      label: takeMessage.formitem.currentidfield.name || '当前节点ID属性',
      value: 'currentIdField',
    },
    {
      label: takeMessage.formitem.currentlabelfield.name || '当前节点Text属性',
      value: 'labelField',
    },
    {
      label: takeMessage.formitem.parentidfield.name || '父节点ID属性',
      value: 'parentIdField',
    },
    {
      label: takeMessage.formitem.searchkey.name || '搜索字段',
      value: 'searchKey',
    },
  ];

  const columns = useMemo(() => {
    return [
      {
        dataIndex: 'field',
        title: '显示属性',
        isIdentical: true,
        editData: {
          type: 'Select' as any,
          options: fields.map((item) => ({ lable: item.label, value: item.value })),
          showSearch: true,
          rules: [
            {
              required: true,
            },
          ],
          afterEdit: (index, record) => {
            const label = fields?.find(ele => ele.value == record.field)!.columnName
            return {
              ...record,
              label
            }
          }
        },
        render: (v: string) => fields.find((item) => item.value === v)?.label || v,
      },
      {
        dataIndex: 'label',
        title: '显示列名',
        isIdentical: true,
        editData: {
          type: 'MultilingualInput' as any,
        },
      },
    ];
  }, [fields]);

  const onAdd = useCallback(() => {
    return { key: uuid(0, 15) };
  }, []);

  const showModal = () => {
    if (!globalForm.fields?.['form.senior.soure.x-component-props.sourceModel']?.value) {
      message.warn('请先选择查询数据源');
      return;
    }
    setVisible(true);
  };

  const onCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  const onOk = async () => {
    const formValue = await form.validateFields();
    const result = FormOtions.reduce(
      (sum, { value: key }) => ({ ...sum, [key]: formValue[key] }),
      {},
    );
    if (type === 'list') {
      try {
        const list = await tableRef.current.getData();
        onChange({ ...result, type, fieldOptions: list } as IValue);
        setVisible(false);
      } catch (e) {
        const msg = typeof e === 'object' && e?.msg;
        // msg && message.error(msg);
      }
    } else {
      onChange({ ...result, type } as IValue);
      setVisible(false);
    }
  };

  useEffect(() => {
    if (visible) {
      setFieldOptions(
        value?.fieldOptions?.length
          ? value?.fieldOptions.filter((ele) => fields.some((child) => child.value === ele.field))
          : fields.map((item) => {
              return {
                key: uuid(0, 15),
                field: item.value,
                label: item.columnName,
              };
            }),
      );
      setType(value?.type || 'list');

      //数据源变更后，需要删除没有的值
      // FormOtions.forEach((ele) => {
      //   const currentValue = value[ele.value];
      //   if (fields.every((child) => child.value !== currentValue)) {
      //     value[ele.value] = null;
      //   }
      // });
      form.setFieldsValue(value);
    }
  }, [value, visible]);

  return (
    <>
      <Button type="primary" onClick={showModal}>
        {getMessage('Transfer.button.config')}
      </Button>
      <ModalAntd
        className={prefixCls}
        title={getMessage('Transfer.button.config')}
        visible={visible}
        width={600}
        bodyStyle={{
          padding: '32px 64px',
          overflow: 'auto',
          maxHeight: 598,
        }}
        onCancel={onCancel}
        onOk={onOk}
        okText={<TextWidget>global.sure</TextWidget>}
        cancelText={<TextWidget>global.cancel</TextWidget>}
        destroyOnClose
      >
        <Form form={form} labelCol={{ span: 7 }} wrapperCol={{ span: 17 }} labelAlign="left">
          <Form.Item
            label={takeMessage.formitem.type.name || '数据类型'}
            className={`${prefixCls}-formItem-horizontal`}
            name="type"
            initialValue={type}
          >
            <Radio.Group
              onChange={({ target: { value } }) => {
                form.setFieldsValue({
                  ...form.getFieldsValue(true),
                  currentIdField: '',
                  labelField: '',
                  parentIdField: '',
                  searchKey: '',
                });
                setType(value);
              }}
            >
              <Radio value="list">{takeMessage.formitem.type.valuelist || '列表'}</Radio>
              <Radio value="tree">{takeMessage.formitem.type.valuetree || '树型'}</Radio>
            </Radio.Group>
          </Form.Item>
          {type === 'tree' &&
            FormOtions.filter((item) => item.value !== 'searchKey').map((item) => (
              <Form.Item
                key={item.value}
                name={item.value}
                label={item.label}
                rules={[{ required: true, message: takeMessage.requiredmessage || '该字段必填' }]}
              >
                <Select
                showSearch
                filterOption={(input, option) =>
                  (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
                }
                 allowClear>
                  {fields.map((option) => (
                    <Option
                      key={option.value}
                      value={`${
                        option.origin_FieldName?.split('$')?.[1]
                          ? option.origin_FieldName?.split('$')?.[1]
                          : ''
                      }$${option.value}`}
                    >
                      {option.value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            ))}
          {type === 'list' && (
            <>
              {FormOtions.filter((item) =>
                ['searchKey', 'currentIdField'].includes(item.value),
              ).map((item) => (
                <Form.Item
                  key={item.value}
                  name={item.value}
                  label={item.label}
                  rules={[{ required: true, message: takeMessage.requiredmessage || '该字段必填' }]}
                >
                  <Select
                showSearch
                filterOption={(input, option) =>
                 (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
               }                  
                   allowClear>
                    {fields.map((option) => (
                      <Option key={option.value} value={option.value}>
                        {option.value}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              ))}

              <EditableTable
                dataSource={fieldOptions}
                columns={columns}
                rowKey="key"
                onAdd={onAdd}
                scroll={{ y: 260 }}
                ref={tableRef}
              />
            </>
          )}
        </Form>
      </ModalAntd>
    </>
  );
};

export default ConfigModal;
